<template>
    <div class="xiaoquan-pager" :class="{[`xiaoquan-pager--${type}`]: type, [`xiaoquan-pager--${size}`]: size}">
        <a @click.prevent="goToFirstPage" :class="currentPage === 1 ? 'disabled' : ''">首页</a>
        <a @click.prevent="prevClick" :class="currentPage === 1 ? 'disabled' : ''">
            <XiaoQuan-Icon icon="angles-left"></XiaoQuan-Icon>
        </a>
        <a @click.prevent="goToFirstPage" v-if="total > pagerCount && currentPage > 5">1</a>
        <a v-if="total > pagerCount && currentPage > 5">
            <XiaoQuan-Icon icon="ellipsis" size="sm"></XiaoQuan-Icon>
        </a>
        <a
            v-for="page in pager" :key="page" :class="page === currentPage ? 'active' : ''"
            @click.prevent="pageClick(page)"
        >{{ page }}</a>

        <a v-if="total > pagerCount && currentPage < total - 4">
            <XiaoQuan-Icon icon="ellipsis" size="sm"></XiaoQuan-Icon>
        </a>
        <a @click.prevent="goToLastPage" v-if="total > pagerCount && currentPage < total - 4">{{ total }}</a>
        <a @click.prevent="nextClick" :class="currentPage === total ? 'disabled' : ''">
            <XiaoQuan-Icon icon="angles-right"></XiaoQuan-Icon>
        </a>
        <a @click.prevent="goToLastPage" :class="currentPage === total ? 'disabled' : ''">尾页</a>
    </div>
</template>

<script setup>
import {computed} from "vue";
import propsObj from "./props";

defineOptions({
    name: "XiaoQuan-Pager"
});
const props = defineProps(propsObj);
const emit = defineEmits(['currentChange']);
const pager = computed(() => {
    const renderPage = []; // 存放要渲染的页码
    if (props.total < props.pagerCount) { // 总页码数 < 页码最大能够显示的数量 = 即全部渲染
        for (let i = 1; i <= props.total; i++) {
            renderPage.push(i);
        }
    } else {
        // 当前页码比较靠前：[1] 2 3 4 5 ... 20
        // 当前页码比较靠中：1 ... 5 6 [7] 8 9 ... 20
        // 当前页码比较靠后：1 ... 16 17 18 19 [20]
        if (props.currentPage <= 5) { // 靠前
            for (let i = 1; i <= 5; i++) {
                renderPage.push(i);
            }
        } else if (props.currentPage >= props.total - 4) { // 靠后
            for (let i = props.total - 4; i <= props.total; i++) {
                renderPage.push(i);
            }
        } else { // 靠中
            for (let i = props.currentPage - 2; i <= props.currentPage + 2; i++) {
                renderPage.push(i);
            }
        }
    }
    return renderPage;
});
const goToFirstPage = () => {
    emit('currentChange', 1);
}
const goToLastPage = () => {
    emit('currentChange', props.total);
}
const prevClick = () => {
    if (!props.currentPage) return;
    emit('currentChange', props.currentPage - 1);
}
const nextClick = () => {
    if (props.total === props.currentPage) return;
    emit('currentChange', props.currentPage + 1);
}

const pageClick = (page) => {
    emit('currentChange', page);
}
</script>

<style scoped lang="scss">

</style>